/*
 * 创建日期 2009-12-14
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.table;

import  org.fantasy.common.db.bean.Cell;
import  org.fantasy.common.db.bean.ReportCell;
import  org.fantasy.common.db.bean.ReportRow;
import  org.fantasy.common.grid.bean.Column;
import  org.fantasy.common.grid.bean.ReportParam;
import  org.fantasy.common.grid.report.ReportHtmlBuilder;
import  org.fantasy.common.grid.util.GridConst;
import  org.fantasy.common.util.Debug;
import  org.fantasy.common.util.StringUtil;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 报表HTML构造器
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-14
 */
public class GridTableBuilder extends ReportHtmlBuilder {

    private static final Log log = LogFactory.getLog(GridTableBuilder.class);

    public GridTableBuilder(ReportParam param) throws Exception {
        super(param);
    }

    /**
     * 构建表头
     * 
     * @throws Exception
     */
    @Override
    protected StringBuffer buildHead() throws Exception {
        StringBuffer html = new StringBuffer(1024);
        html.append("<thead>\n");
        for (List<Column> columns : tableHeads) {
            html.append("<tr class='lock'>\n");
            for (int i = 0; i < columns.size(); i++) {
                Column col = columns.get(i);
                html.append("<th ");

                html.append(" id='" + col.getId() + "'");
                html.append(" col='" + col.getDesc() + "'");
                html.append(" sort='" + col.isField() + "'");
                html.append(" nowrap='nowrap'");
                
                if (StringUtil.isValid(col.getDetail()))
                    html.append(" detail='" + col.getDetail() + "'");
                
                if (StringUtil.isValid(col.getColspan()))
                    html.append(" colspan='" + col.getColspan() + "'");

                if (StringUtil.isValid(col.getRowspan()))
                    html.append(" rowspan='" + col.getRowspan() + "'");

                if (param.isHideCol(col))
                    html.append(" style='display:none' ");

                if (StringUtil.isValid(col.getDataType()))
                    html.append(" dataType='" + col.getDataType() + "'");
                else
                    html.append(" dataType='string'");

                if (StringUtil.isValid(col.getWidth()))
                    html.append(" width='" + col.getWidth() + "'");

                if (StringUtil.isValid(col.getComment()))
                    html.append(" title='" + col.getComment() + "'");
                
                String label = StringUtil.asString(col.getFieldLabel());
                html.append(">");
                
                if( !col.isCheckboxType() ){
                    html.append("<span class='thsort'>" + label + "</span>");
                }else{
                    html.append("<span class='thsort'>");
                    html.append("<span id='CHECKBOX_TOGGLE' class='uncheck'/>");
                    html.append("</span>");
                }
                    
                html.append("</th>\n");
            }
            html.append("</tr>\n");
        }
        html.append("</thead>\n");
        return html;
    }

    /**
     * 构建表体
     * 
     * @throws Exception
     */
    @Override
    protected StringBuffer buildBody() throws Exception {
        StringBuffer html = new StringBuffer(1024);
        for (int i = 0; i < resultList.size(); i++) {
            ReportRow row = resultList.get(i);
            String rowID = "row" + i;
            row.put(GridConst.ROW_ID,new Cell(rowID));
            html.append("<tr id='" + rowID + "' index='" + i + "' " + getRowStyle(row, i));
            html.append(">\n");
            html.append(buildCells(row));
            html.append("</tr>\n");
        }
        return html;
    }

    /**
     * 构造一行中的所有列
     * 
     * @return
     */
    @Override
    protected StringBuffer buildCells(ReportRow row) throws Exception {
        StringBuffer html = new StringBuffer(1024);
        for (int i = 0; i < tableFields.size(); i++) {
            Column col = tableFields.get(i);
            String colName = col.getId();
            String colValue = cellCustom.getValue(row, col);
            ReportCell reportCell = row.getReportCell(colName);
            if (reportCell.isTop()) {
                html.append("<td");
                if (reportCell.getRowspan() > 1) {
                    html.append(" valign='middle' rowspan='" + reportCell.getRowspan() + "'");
                }
            } else {
                continue;
            }
            html.append(" col='" + colName + "'");

            if (StringUtil.isValid(col.getAlign()))
                html.append(" align='" + col.getAlign() + "'");
            else if (col.isNumberType()) // 默认数字居右
                html.append(" align='right'");

            // 是否显示
            if (param.isHideCol(col)) {
                html.append(" style='display:none'");
            } else { // 显示样式
                html.append(" " + getCellStyle(row, col));
            }

            // 列宽
            if (StringUtil.isValid(col.getWidth()))
                html.append(" width='" + col.getWidth() + "'");
            else
                html.append(" nowrap='nowrap'");

            // 行高
            if (StringUtil.isValid(rowHeight))
                html.append(" height='" + rowHeight + "'");

            html.append(">");

            if (StringUtil.isValid(col.getClick())) {
                if (!(row.isSubTotal() || row.isSumTotal())) {
                    String onclick = getOnClickString(row, col.getClick());
                    html.append("<a href=\"javascript:" + onclick + "\" onclick='_StopBubble(event)'>");
                    html.append(colValue);
                    html.append("</a>");
                } else {
                    html.append(colValue);
                }
            } else {
                html.append(colValue);
            }
            html.append("</td>\n");
        }
        return html;
    }

    /**
     * 取得格式化后的onClick
     * 
     * @return
     */
    @Override
    protected String getOnClickString(ReportRow row, String onClick) {
        List<String> params = StringUtil.matchs(onClick, "#\\s*\\w+\\s*#");
        for (String param : params) {
            String paramKey = param.replaceAll("^#|#$", "").trim();
            String paramValue = row.getCell(paramKey).getString();
            onClick = onClick.replaceAll("#\\s*" + paramKey + "\\s*#", paramValue);
        }
        return onClick;
    }

    @Override
    public Object getReport() throws Exception {
        Debug debug = new Debug("Report");
        debug.start("Building Report");
        StringBuffer html = new StringBuffer(1024 * 8);
        html.append("<table class=\"rtable\" cellspacing='0' border=\"0\" cellpadding='0'> \n");
        html.append(this.buildHead());
        html.append("   <tbody>\n");
        html.append(this.buildBody());
        html.append("   </tbody>\n");
        html.append("</table> \n");
        debug.end("Building Report");
        // log.info(debug);
        return html;
    }
}
